package com.bayair.doctor.ui.inquiry_record;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.bayair.doctor.R;
import com.bayair.doctor.ui.chat.ChatActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.qcloud.tim.uikit.component.CustomLinearLayoutManager;
import com.tencent.qcloud.tim.uikit.component.action.PopDialogAdapter;
import com.tencent.qcloud.tim.uikit.component.action.PopMenuAction;
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo;
import com.tencent.qcloud.tim.uikit.modules.conversation.base.ConversationInfo;
import com.tencent.qcloud.tim.uikit.utils.PopWindowUtil;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 会话布局（里面管理有pop、adapter）
 */
public class SessionLayout extends RecyclerView implements
        BaseQuickAdapter.OnItemClickListener,
        BaseQuickAdapter.OnItemLongClickListener {

    //adapter相关
    private InquiryRecordAdapter mAdapter;
    private List<ConversationInfo> mInfos = new ArrayList<>();

    //Pop相关
    private List<PopMenuAction> mPopActions = new ArrayList<>();//pop的item
    private ListView mPopListView;
    private PopDialogAdapter mPopAdapter;
    private PopupWindow mPopWindow;

    public SessionLayout(@NonNull Context context) {
        super(context);
        init();
    }

    public SessionLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SessionLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void init() {
        setLayoutFrozen(false);
        setItemViewCacheSize(0);
        setHasFixedSize(true);
        setFocusableInTouchMode(false);
        CustomLinearLayoutManager linearLayoutManager = new CustomLinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        setLayoutManager(linearLayoutManager);

        mAdapter = new InquiryRecordAdapter(mInfos);
        setListener();
        setAdapter(mAdapter);
        initPop();

    }

    private void setListener() {
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemLongClickListener(this);
    }

    //初始化Pop
    private void initPop() {
        List<PopMenuAction> conversationPopActions = new ArrayList<PopMenuAction>();
        //置顶聊天
        PopMenuAction action = new PopMenuAction();
        action.setActionName(getResources().getString(R.string.chat_top));
        action.setActionClickListener((position, data) -> {
            SessionDataKit.instance().setConversationTop(position, (ConversationInfo) data);
        });
        conversationPopActions.add(action);
        //删除会话
        action = new PopMenuAction();
        action.setActionName(getResources().getString(R.string.chat_delete));
        action.setActionClickListener((position, data) -> {
            SessionDataKit.instance().deleteConversation(position, (ConversationInfo) data);
        });
        conversationPopActions.add(action);

        mPopActions.clear();
        mPopActions.addAll(conversationPopActions);
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        startChatActivity(mInfos.get(position));
    }

    @Override
    public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
        startPopShow(view, position, mInfos.get(position));
        return true;
    }


    /**
     进入对应会话的聊天页面
     */
    private void startChatActivity(ConversationInfo conversationInfo) {
        ChatInfo chatInfo = new ChatInfo();
        chatInfo.setType(conversationInfo.isGroup() ? TIMConversationType.Group : TIMConversationType.C2C);
        chatInfo.setId(conversationInfo.getId());
        chatInfo.setChatName(conversationInfo.getTitle());
        ChatActivity.actionStart(chatInfo);
    }


    /**
     显示置顶Pop
     */
    private void startPopShow(View view, int position, ConversationInfo info) {
        showItemPopMenu(position, info, view.getX(), view.getY() + view.getHeight() / 2);
    }

    /**
     长按会话item弹框

     @param index     会话序列号
     @param info      会话数据对象
     @param locationX 长按时X坐标
     @param locationY 长按时Y坐标
     */
    private void showItemPopMenu(int index, ConversationInfo info, float locationX, float locationY) {
        if (mPopActions == null || mPopActions.size() == 0)
            return;
        View itemPop = LayoutInflater.from(getContext()).inflate(R.layout.pop_menu_layout, null);
        mPopListView = itemPop.findViewById(R.id.pop_menu_list);
        mPopListView.setOnItemClickListener((parent, view, position, id) -> {
            PopMenuAction action = mPopActions.get(position);
            if (action.getActionClickListener() != null) {
                action.getActionClickListener().onActionClick(index, info);
            }
            mPopWindow.dismiss();
        });

        for (int i = 0; i < mPopActions.size(); i++) {
            PopMenuAction action = mPopActions.get(i);
            if (info.isTop()) {
                if (action.getActionName().equals(getResources().getString(R.string.chat_top))) {
                    action.setActionName(getResources().getString(R.string.quit_chat_top));
                }
            } else {
                if (action.getActionName().equals(getResources().getString(R.string.quit_chat_top))) {
                    action.setActionName(getResources().getString(R.string.chat_top));
                }

            }
        }
        mPopAdapter = new PopDialogAdapter();
        mPopListView.setAdapter(mPopAdapter);
        mPopAdapter.setDataSource(mPopActions);
        mPopWindow = PopWindowUtil.popupWindow(itemPop, this, (int) locationX, (int) locationY);

        //延迟10自动dismiss
        postDelayed(() -> mPopWindow.dismiss(), 10000);
    }

    //------------------对外暴露方法------------------------------------------------

    public void updateDataList(List<ConversationInfo> data) {
        this.mInfos = data;
        mAdapter.setNewData(mInfos);
    }

    //刷新
    public void updateSingleData(ConversationInfo info) {
        mAdapter.notifyDataSetChanged();
    }

    //添加会话
    public void addConversationInfo(int position, ConversationInfo info) {
        mInfos.add(position, info);
        mAdapter.notifyItemInserted(position);
        mAdapter.notifyDataSetChanged();
    }

    //移除会话
    public void removeConversationInfo(int position) {
        mInfos.remove(position);
        mAdapter.notifyItemRemoved(position);
        mAdapter.notifyDataSetChanged();
    }
}
